package br.com.mtech.ctrlliberty.ejb.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.com.mtech.ctrlliberty.clientjar.entity.CamposPesquisaVO;
import br.com.mtech.ctrlliberty.clientjar.entity.InternetVO;
import br.com.mtech.ctrlliberty.clientjar.entity.TelefoneVO;
import br.com.mtech.ctrlliberty.clientjar.util.Util;

/**
 * Session Bean implementation class InternetEJBDAO
 */
@Stateless
public class InternetEJBDAO implements InternetEJBDAOLocal {

	@PersistenceContext(unitName="CtrlLiberty")	
	EntityManager	entityManager;
	
	@Override
	public InternetVO recuperar(Long id) {
		return entityManager.find(InternetVO.class, id);
	}
	
	@Override
	public InternetVO inserir(InternetVO site){
		entityManager.persist(site);
		return site;
	}  
	
	@Override
	@SuppressWarnings("unchecked")
	public List<InternetVO> pesquisarSites(TelefoneVO telefone, CamposPesquisaVO campos) {
		
		StringBuilder strQuery = new StringBuilder();
		
		strQuery.append("from InternetVO internet ");
		strQuery.append("where internet.telefone = :tel ");
		strQuery.append("and internet.dataAcesso between :dataInicial and :dataFinal");
		
		if(!Util.isEmpty(campos.getDescricaoSite())) {
			strQuery.append("and internet.nmSite like :descricaoSite ");
		}
		if(!Util.isEmpty(campos.getDescricaoUrl())) {
			strQuery.append("and internet.url like :descricaoUrl ");
		}
			
		Query query = entityManager.createQuery(strQuery.toString());
		query.setParameter("dataInicial", campos.getDataInicial().getTime());		
		query.setParameter("dataFinal", campos.getDataFinal().getTime());
		query.setParameter("tel", telefone);
				
		if(!Util.isEmpty(campos.getDescricaoSite())) {
			query.setParameter("descricaoSite", campos.getDescricaoSite() + "%");
		}
		if(!Util.isEmpty(campos.getDescricaoUrl())) {
			query.setParameter("descricaoSite", "%" + campos.getDescricaoUrl() + "%");
		}
		if(campos.getTipoLigSms() != null) {
			query.setParameter("tipoSms", campos.getTipoLigSms());
		}
		
		return query.getResultList();
	}

}
